import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_baseview/utils/cache_util.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
// ignore: library_prefixes
import 'package:get/get.dart' as GetX;
import '../lib_baseview/root_page.dart';
import '../lib_runtime/logger.dart';
import '../lib_user/user_manager.dart';
import '../m_login/os_login_page.dart';
import '../resource/language/generated/l10n.dart';

class HeaderInterceptor extends Interceptor {
  static const String tag = 'HeaderInterceptor';

  static bool isLoginOut = false;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    var userId = UserManager.instance.currentUser?.userId ?? '';
    var token = UserManager.instance.currentUser?.token ??
        'APP-a0fd5d9f9160444dbe10db9d0e741d65#2060392';

    options.headers.addAll({
      "Accept-Language": _getLocale()?.languageCode ?? 'en',
      "token": token,
      "userid": userId,
      "device-cert": "",
      // "X-Request-Id": 'ios_$tempStr',
      "X-App-Type": '1',
      "requestHost": 'app',
      "version": '2.9.3',
      "Content-Type": "application/x-www-form-urlencoded",
    });

    RLog.d("$tag onRequest options:$options handler:$handler");

    super.onRequest(options, handler);
  }

  // @override
  // void onResponse(Response response, ResponseInterceptorHandler handler) {
  //   RLog.d(
  //       'onResponse:${response.requestOptions.uri.path} hashCode:${response.requestOptions.hashCode} data:${response.data}');
  //   _handelLogoutAction(response);
  //   return super.onResponse(response, handler);
  // }

  Locale? _getLocale() {
    // 优先使用缓存的语言
    final cachedLangCode = CacheUtil.get(CacheKeys.languageCode);
    if (cachedLangCode.isNotEmpty) {
      return Locale(cachedLangCode);
    }

    // 其次使用 GetX 管理的语言
    if (GetX.Get.locale != null) return GetX.Get.locale;

    // 默认第一个支持的语言
    final supportedLocales = T.delegate.supportedLocales;
    if (supportedLocales.isNotEmpty) {
      return supportedLocales.first;
    }

    return null;
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    final map = response.data;
    RLog.d("$tag onResponse response:$response");
    if (map case {'status': int status, 'msg': String msg}) {
      switch (status) {
        case 200:

          // response.data = map['data'];
          handler.next(response);

        // 被踢出
        case 401 || 10006:
        // RLog.w("status:$status msg:$msg");
        // // 某些错误携带额外的data字段
        // Get.find<AccountService>()
        //     .logout(msg, ApiStatus(status), map['data']);
        // handler.reject(DioException(
        //   requestOptions: response.requestOptions,
        //   response: response,
        //   type: DioExceptionType.badResponse,
        //   message: msg,
        // ));

        case 500:
          handler.reject(DioException(
            requestOptions: response.requestOptions,
            response: response,
            type: DioExceptionType.badResponse,
            message: msg,
          ));

        /// 登录失效
        case 501:

          /// 跳转到首页
          rootNavigatorState.currentState?.pushReplacement(
            MaterialPageRoute(
              builder: (context) => const OSLoginPage(),
            ),
          );

          UserManager.instance.logout(isLogoutResp: false);

          handler.reject(DioException(
            requestOptions: response.requestOptions,
            response: response,
            type: DioExceptionType.badResponse,
            message: msg,
          ));

        // 余额不足，特殊处理
        case 12001:
          // logger.w("status:$status msg:$msg");
          // if (response.requestOptions.extra case {'showError': true}) {
          //   'Out of $kDiamondCapName, please recharge.'.toast();
          // }

          // // 顾问主页点击下单，因余额不足触发跳转充值页
          // if ('/psychic'.isCurrentRoute || '/listener'.isCurrentRoute) {
          //   Get.toNamed('/recharge', parameters: {'upstream': 'advisorpage'});
          // } else if (r'^/im/advisor/[^/]+$'.isCurrentRouteReg) {
          //   Get.toNamed('/recharge', parameters: {'upstream': 'impage'});
          // } else {
          //   Get.toNamed('/recharge');
          // }
          handler.reject(DioException(
            requestOptions: response.requestOptions,
            response: response,
            type: DioExceptionType.badResponse,
            message: msg,
          ));
        default:
          // logger.w("status:$status msg:$msg");
          // if (response.requestOptions.extra case {'showError': true}) {
          //   msg.toast();
          // }
          // EventBus().emit(EventName.apiError.value, {
          //   'status': status,
          // });

          showToast('${map['status']} + ${map['msg']}');

          handler.reject(DioException(
            requestOptions: response.requestOptions,
            response: response,
            type: DioExceptionType.badResponse,
            message: msg,
          ));
      }
    } else {
      RLog.w("Wrong format:$map");
      handler.reject(DioException(
        requestOptions: response.requestOptions,
        response: response,
        type: DioExceptionType.badResponse,
      ));
    }
  }

  // @override
  // void onError(DioException err, ErrorInterceptorHandler handler) {
  //   logger.w('onError: $err');
  //   super.onError(err, handler);
  // }

  @override
  void onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) {
    RLog.d(
        'onError:${err.requestOptions.uri.path} hashCode:${err.requestOptions.hashCode} data:${err.response?.data}');
    // _handelLogoutAction(err.response);
    return super.onError(err, handler);
  }

  // _handelLogoutAction(Response? response) {
  //   try {
  //     if (response != null) {
  //       RLog.d('response $response');

  //       // /// 通过header 特定code优化，不用每次解析body
  //       // Headers headers = response.headers;
  //       // String? dfCode = headers.value('x-df-rsp-code');
  //       // if(dfCode == '1001110004'){ // token失效
  //       //   if (!isLoginOut) {
  //       //     isLoginOut = true;
  //       //     GlobalRoutesAction.loginOutAction();
  //       //   }
  //       // }else{
  //       //   isLoginOut = false;
  //       // }
  //     }
  //   } catch (e) {
  //     RLog.d("_handelLogoutAction error $e");
  //   }
  // }
}
